<?php

/**
 * This file is part of the Framework03 PHP framework.
 * @author Walter Tamboer
 * @package Framework03
 */

class FW_Session
{
    /**
     * @var bool Whether or not a session has already been started.
     */
    private static $sessionStarted = false;
    
    /**
     * @var FW_Session_SaveHandler_Abstract The session save handler used to save sessions.
     */
    private static $saveHandler = null;

    /**
     * Starts a new session.
     * @throws FW_Session_Exception
     */
    public static function start()
    {
        if (!self::$sessionStarted)
        {
            if (headers_sent($filename, $linenum))
                throw new FW_Session_Exception("Session must be started before any output has been sent to the browser; output started in {$filename}/{$linenum}");

            self::$sessionStarted = true;

            session_start();
        }
    }
    
    /**
     * Sets the session save handler so that we're able to manage sessions.
     * @param FW_Session_SaveHandler_Abstract $handler
     */
    public static function setSaveHandler(FW_Session_SaveHandler_Abstract $handler)
    {
        session_set_save_handler(
            array(&$handler, 'open'),
            array(&$handler, 'close'),
            array(&$handler, 'read'),
            array(&$handler, 'write'),
            array(&$handler, 'destroy'),
            array(&$handler, 'gc')
        );
        
        self::$saveHandler = $handler;
    }
}
